package servlet;

import cn.cvs.dao.MovieMapper;
import cn.cvs.pojo.Movie;
import cn.cvs.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/AddServlet")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        SqlSession sqlSession= MyBatisUtil.createSqlSession();
        MovieMapper movieMapper=sqlSession.getMapper(MovieMapper.class);
        Movie movie=new Movie();
        movie.setMovieName(req.getParameter("movieName"));
        movie.setMovieType(req.getParameter("movieType"));
        movie.setPrice(Double.parseDouble(req.getParameter("price")));
        movie.setRecommend(Integer.parseInt(req.getParameter("recommend")));
        movie.setStartTime(req.getParameter("startTime"));
        movie.setEndTime(req.getParameter("endTime"));
        movie.setVotes(Integer.parseInt(req.getParameter("votes")));
        PrintWriter out= resp.getWriter();
        int count=movieMapper.add(movie);
        if (count>0){
            out.print("<script>\n" +
                    "    alert(\"添加成功\")\n" +
                    "    location.href=\"ListServlet\"\n" +
                    "  </script>");
        }else {
            out.print("<script>\n" +
                    "    alert(\"添加失败\")\n" +
                    "    location.href=\"add.jsp\"\n" +
                    "  </script>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
